# -*- coding: utf-8 -*-
"""
base_page.py
2025/8/31
@author: minghui
"""

import os
from datetime import datetime

from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait


class BasePage:
    """所有 Page 的基类"""

    # 项目根目录下统一截图目录
    SCREENSHOT_DIR = os.path.join(
        os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
        "screenshots"
    )

    def __init__(self, driver: WebDriver, timeout: int = 10):
        self.driver = driver
        self.wait = WebDriverWait(driver, timeout)
        # 如果目录不存在自动创建
        os.makedirs(self.SCREENSHOT_DIR, exist_ok=True)

    # ---------- 已有公共方法 ----------
    def find(self, locator):
        return self.wait.until(EC.visibility_of_element_located(locator))

    def click(self, locator):
        self.find(locator).click()

    def send_keys(self, locator, text: str):
        ele = self.find(locator)
        ele.clear()
        ele.send_keys(text)

    # ---------- 新增截图 ----------
    def save_screenshot(self, prefix: str = "error") -> str:
        """
        截图并以时间戳命名，返回完整文件路径
        :param prefix: 文件名前缀，便于分类
        :return: 文件绝对路径
        """
        ts = datetime.now().strftime("%Y%m%d_%H%M%S_%f")[:-3]  # 毫秒
        file_name = f"{prefix}_{ts}.png"
        file_path = os.path.join(self.SCREENSHOT_DIR, file_name)
        self.driver.save_screenshot(file_path)
        return file_path
